import Common from "../../Common";
import ListsField from "./ListsField";

const {ccclass, property} = cc._decorator;

/**
 * 列表项
 */
@ccclass
export default class ListsItem extends Common {

    @property(cc.Node)
    header: cc.Node;

    @property(cc.Node)
    content: cc.Node;

    fieldPrefab: cc.Prefab

    init(title: string, fields: any[], desc?: string, titleColor?: string) {
        this.header.getChildByName('title').getComponent(cc.Label).string = title
        if (titleColor) {
            // @ts-ignore
            this.header.getChildByName('title').color = cc.color(titleColor);
        }
        if (desc) {
            this.header.getChildByName('desc').getComponent(cc.Label).string = desc
        }
        fields.forEach(item => {
            this.attachField(item.label, item.value)
        })
    }

    async attachField(label: string, value: string) {
        const fieldPrefab = await this.getFieldPrefab();
        const fieldNode = cc.instantiate(fieldPrefab)
        fieldNode.getComponent(ListsField).init(label, value)
        this.content.addChild(fieldNode)
    }


    async getFieldPrefab() {
        if (!this.fieldPrefab) {
            this.fieldPrefab = await this.getPrefab('lists/field')
        }
        return this.fieldPrefab
    }
}
